package net.androy.smugmugtool.smugmugapi;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import net.androy.smugmugtool.XMLHandler;
import net.androy.smugmugtool.SearchActivity.ImageAdapter;
import net.androy.smugmugtool.vo.LoginInfo;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ImageView;

public class SmugmuAPIManager implements SmugmugAPI {

    private final static String APIURL = "https://api.smugmug.com/hack/json/1.2.0/";
    private final static String SEARCHURL = "http://api.smugmug.com/hack/feed.mg?Type=keyword&format=rss&Data=";
    private final static String APIKEY = "thzGz6D3jIfhU6QabQDvKLQr9wg6lahB";
    private final static SmugmuAPIManager instance = new SmugmuAPIManager();

    private SmugmuAPIManager() {
    }

    public static SmugmuAPIManager getInstance() {
	return instance;
    }

    public LoginInfo login(String username, String password) {

	try {
	    String request = buildLoginRequest(username, password);
	    Log.d("Login Request", request);

	    return sendPost(request);
	} catch (Exception e) {
	    e.printStackTrace();
	}

	return null;
    }
    
    
   
    private String buildLoginRequest(String username, String password) throws UnsupportedEncodingException {
	StringBuilder builder = new StringBuilder(APIURL);
	builder.append("?");
	builder.append("method="+URLEncoder.encode("smugmug.login.withPassword", "UTF-8"));
	builder.append("&APIKey=" + URLEncoder.encode(APIKEY, "UTF-8"));
	builder.append("&EmailAddress=" + URLEncoder.encode(username, "UTF-8"));
	builder.append("&Password=" + URLEncoder.encode(password, "UTF-8"));

	return builder.toString();

    }

    private LoginInfo sendPost(String url) throws Exception {
	HttpUriRequest request = null;
	HttpResponse response = null;

	DefaultHttpClient client = new DefaultHttpClient();

	request = new HttpGet(url);
	response = client.execute(request);
	HttpEntity entity = response.getEntity();
	
	Log.d("status:::: ", response.getStatusLine().getStatusCode()+"");
	

	BufferedReader reader = new BufferedReader(new InputStreamReader(entity
		.getContent()));
	
	StringBuilder builder = new StringBuilder();
	String line = "";
	while ((line = reader.readLine()) != null) {
	    Log.d("Response", line);
	    builder.append(line);
	}

	reader.close();
	
	
	return buildLoginInfo(builder.toString());

    }
    
    
    private LoginInfo buildLoginInfo(String response) throws JSONException{
	
	JSONObject root = new JSONObject(response);
	LoginInfo info = new LoginInfo();
	String stat = root.getString("stat");
	if(stat == null || stat.equals("fail")){
	    return null;
	}
	
	info.setStat(stat);
	info.setMethod(root.getString("method"));
	root = root.getJSONObject("Login");
	JSONObject userObject = root.getJSONObject("User");
	
	LoginInfo.User user = new LoginInfo.User();
	user.setId(Integer.parseInt(userObject.getString("id")));
	user.setDisplayName(userObject.getString("DisplayName"));
	user.setNickname(userObject.getString("NickName"));
	
	info.setUser(user);
	info.setPasswordHash(root.getString("PasswordHash"));
	info.setAccountType(root.getString("AccountType"));
	info.setFileSizeLimit(root.getString("FileSizeLimit"));
	info.setSmugVault(Boolean.valueOf(root.getString("SmugVault")));
	info.setSession(((JSONObject) root.getJSONObject("Session")).getString("id"));
	
	return info;
    }

}
